package com.cn.ycy.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {

  /**
   * jdk动态代理
   */
  @org.junit.Test
  public void test0() {
    Student students = new Student();

    /**
     * 1 代理类 不用显示声明
     * 2 没有显示声明代理类，所以被代理类 方法不用重复声明
     *
     */
    Object o = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{Person.class},
            new InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("我是proxy，ido first");
                return method.invoke(students, args);
              }
            });

    Person studentsProxy = (Person) o;
    studentsProxy.doWork();
  }

  @org.junit.Test
  public void test1() {
    // 实例化 被代理对象
    Student students = new Student();
    Object o = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{Person.class},
            new CustomInvocationHandler3(students));
    Person studentsProxy = (Person) o;
    studentsProxy.doWork();
  }

  /**
   * 多层嵌套 动态代理
   */
  @org.junit.Test
  public void test3() {
    Student student = new Student();
    CustomInvocationHandler3 customInvocationHandler = new CustomInvocationHandler3(student);
    Person o = (Person) Proxy.newProxyInstance(student.getClass().getClassLoader(), new Class[]{Person.class}, customInvocationHandler);

    CustomInvocationHandler2 customInvocationHandler2 = new CustomInvocationHandler2(o);
    Person o1 = (Person) Proxy.newProxyInstance(student.getClass().getClassLoader(), new Class[]{Person.class}, customInvocationHandler2);
    o1.doWork();

  }


}
